package com.xmltosql;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import com.google.common.base.Converter;
import org.apache.commons.io.FileUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class CreatSql {

    private static JSONObject dicJson = JSONObject.parseObject("");

    private static JSONObject fileJson = JSONObject.parseObject("");

    static {
        File dicFile = new File("dic_dp+ln.json");
        String dicText = null;
        try {
            dicText = FileUtils.readFileToString(dicFile, "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        dicJson = JSONObject.parseObject(dicText);

        File tableFile = new File("table.json");
        String fileText = null;
        try {
            fileText = FileUtils.readFileToString(tableFile, "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        fileJson = JSONObject.parseObject(fileText);
    }

    public static void main(String[] args) throws Exception {
        String pk = "pd";
        int count = 0;
        BufferedWriter bw = new BufferedWriter(new FileWriter("ln_" + pk + ".sql", true));

        //"D:\\project\\pactera\\ecas-new-202210\\ecas-ln\\ecas-ln-dao\\src\\main\\resources\\spring\\ds\\mybatis\\mappers"
        //String xmlPath = "D:\\project\\pactera\\ecas-new-202210\\ecas-dp\\ecas-dp-dao\\src\\main\\resources\\spring\\ds\\mybatis\\mappers";
        String xmlPath = "D:\\project\\pactera\\ecas-new-202210\\ecas-ln\\ecas-ln-dao\\src\\main\\resources\\spring\\ds\\mybatis\\mappers\\" + pk;
        File dirs = new File(xmlPath);
        for (String s : dirs.list()) {
            File xml = new File(xmlPath + "\\" + s);
            if (!xml.isDirectory()) {
                readXml(xmlPath + "\\" + s, bw);
                count++;
            }
        }
        System.out.println("总表数：" + count);
        bw.close();
    }

    private static void readXml(String xmlPath, BufferedWriter bw) throws Exception {

        String tn = "";
        // 创建SAXReader对象
        SAXReader reader = new SAXReader();
        // 加载xml文件
        Document dc = reader.read(new File(xmlPath));
        // 获取根节点
        Element e = dc.getRootElement();
        List<Element> resultMap = e.elements("resultMap");
        //获取表明
        Attribute type = resultMap.get(0).attribute("type");
        String value = type.getValue();
        String[] split = value.split("\\.");
        String tableName = split[split.length - 1];
        Converter<String, String> converter = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.LOWER_UNDERSCORE);
        String table_name = converter.convert(tableName);
        //获取列
        List<Element> results = resultMap.get(0).elements("result");
        bw.write("CREATE TABLE IF NOT EXISTS `" + table_name + "`(");
        bw.newLine();
        for (int i = 0; i < results.size(); i++) {
            //获取id这个属性
            Attribute attribute = results.get(i).attribute("column");
            //获取id的属性值
            String column = attribute.getValue().trim();

            //address NUMERIC(20,2) COMMENT '家庭住址',
            //String columnString = "`" + column + "` VARCHAR(100) comment '" + content + "'";

            JSONObject json = (JSONObject) dicJson.get(column);
            String columnString;
            if (json != null) {

                String notes = json.get("notes").toString();
                String field = json.get("field").toString();
                //String accuracy = json.get("accuracy").toString();
                String javatype = json.get("javatype")!=null?json.get("javatype").toString():"VARCHAR";
                columnString = "";
                if ("DECIMAL".equals(javatype)) {
                    columnString = field + " decimal(20,2) COMMENT '" + notes + "'";
                } else if ("DATE".equals(javatype)) {
                    columnString = field + " date COMMENT '" + notes + "'";
                } else {
                    String leng = json.get("leng")!=null?json.get("leng").toString():"100";
                    columnString = field + " " + javatype + "(" + leng + ") COMMENT '" + notes + "'";
                }
            } else {
                columnString = column + " varchar(100)";
            }

            if (i == 0) {
                bw.write(columnString);
            } else {
                bw.write(",");
                bw.newLine();
                bw.write(columnString);
            }
        }
        bw.newLine();
        String tbnm = fileJson.get(table_name) == null ? "" : fileJson.get(table_name).toString();
        bw.write(")ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='" + tbnm + "';");
        bw.newLine();
        bw.newLine();
        bw.flush();
        System.out.println(table_name + "表已完成");

    }


}
